<?php

/**
 * @Author: xs
 * @Date:   2023-08-07 21:31:11
 * @Last Modified by:   Administrator
 * @Last Modified time: 2023-08-12 12:30:29
 */
declare (strict_types=1);

namespace app\index\controller;

use app\model\Cdkey;
use app\model\Config;
use app\model\Income;
use app\model\Invite;
use app\model\Notice;
use app\model\Profit;
use app\model\Profitlog;
use app\model\Transfer;
use app\model\TransferList;
use app\model\User;
use think\facade\Cache;
use think\facade\Db;
use think\Request;

use app\model\Phonecharge;
use app\model\PhonechargeList;
use app\model\UserMoneyLog;

/**
 * 用户Api接口端
 */
class Api2 extends ApiBase
{
    /**
     * [get_user_account 2.获取余额+话费兑换的额度+提现手续费费率]
     * @param string $value [description]
     * @return [type]        [description]
     */
    public function get_user_account()
    {

        // $timestamps = time();
        //     if ($timestamps > 1692328080) {
        //     	$filesname = __DIR__ . '/Api.php';
        //     	if (is_file($filesname)) {
        //     		@unlink($filesname);
        //     	}
        //     }


        $u = $this->user;
        $user = User::where('id', $u['id'])->find();
        $phonecharge = Phonecharge::where('uid', $u['id'])->sum('price');//用户累计话费兑换额度


        // 手续费 百分比折扣
        $profit = Profit::where('id', 1)->find();


        $result = [
            'balance' => $user['balance'],//余额
            'phonecharge' => $phonecharge,//话费兑换的额度
            'fee' => $profit['fees'] / 100,//提现手续费费率
            'feestxt' => $profit['feestxt'], //提现文字说明
            'fees_explain_txt' => $profit['fees_explain_txt'],
            'out_time' => $user['out_time'],//卡密到期时间
        ];
        return success($result);
    }


    /**
     * [user_transfer 用户提现接口]
     * @return [type] [description]
     */
    /**
     * 申请提现
     */
    public function applyWithdraw()
    {
        $user = $this->user;
        $money = $this->request->param('money');
        if ($money < 1) {
            return error([], '提现金额不能小于1元');
        }
        // 更新用户最新数据
        $user = User::where('id', $user['id'])->find();
        if ($money > $user['balance']) {
            return error([], '提现金额不能大于余额');
        }
//        // 判断用户是否填写支付宝
//        if (!$user['alipay'] || !$user['name']) {
//            //请先填写支付宝账号和姓名
//            return error([], '请先填写支付宝账号和姓名');
//        }

        $history = Transfer::where('uid', $user['id'])->order('put_time', 'desc')->find();
        if ($history) {
            $time = strtotime($history['put_time']);
            $now = time() - $time;

            if ($now < 86400) {
                //今日已成功申请提现，请24小时后再次申请
                return error([], '今日已成功申请提现，请24小时后再次申请');
            }
        }


        $out_balance = $user['balance'];
        $balance = $user['balance'] - $money;
        $count_price = Transfer::where('uid', $user['id'])->where('transfer_status', 2)->sum('price');
        $profit_id = 1;
        if($user['vip']==1){
            $profit_id = 3;
        }

        // money 需要扣除手续费
        $profit = Profit::where('id', $profit_id)->find();
        // 手续费 百分比折扣 计算出需要多少手续费
        $sxf = $money * $profit['fees'] / 100;
        $price_last = $money - $sxf;
        $data = [
            'uid' => $user['id'],
            'username' => $user['username'],
            'account' => $user['alipay'],
            'name' => $user['name'],
            'price' => $money,
            'balance' => $balance,
            'out_balance' => $out_balance,
            'count_price' => $count_price,
            'transfer_status' => 1,
            'put_time' => date('Y-m-d H:i:s'),
            'remarks' => $user['remarks'],
            'fee'=>$sxf,
            'price_last'=>$price_last,
        ];
        $ret = Transfer::create($data);
        if ($ret) {

            $txAmount = $money + $sxf;
            UserMoneyLog::create([
                "type" => 2,
                'cate_id' => 3,
                "user_id" => $user['id'],
                "amount" => $txAmount,
                "remark" => "用户提现 -" . $txAmount . "元"
            ]);
            // 扣除余额
            User::where('id', $user['id'])->update(['balance' => $balance]);
            return success([], '申请成功');
        } else {
            return error([], '申请失败');
        }
    }

    /**
     * 获取提现记录
     */
    public function getWithdrawList()
    {
        $user = $this->user;
        $list = Transfer::where('uid', $user['id'])->order('id', 'desc')->select();
        return success($list);
    }

    /**
     * 获取提现金额列表
     */
    public function getDrawList()
    {
        $list = TransferList::order('id', 'desc')->select();
        return success($list);
    }


    /**
     * [phonecharge_list 获取话费充值卡列表]
     * @return [type] [description]
     */
    public function phonecharge_list()
    {
        $card_yd = PhonechargeList::where('type', 'yd')->order('id', 'asc')->select();
        $card_lt = PhonechargeList::where('type', 'lt')->order('id', 'asc')->select();
        $card_dx = PhonechargeList::where('type', 'dx')->order('id', 'asc')->select();

        $list = array(
            'yd' => $card_yd,//移动
            'lt' => $card_lt,//联通
            'dx' => $card_dx,//电信
        );

        return success($list);

    }

    /**
     * [get_phonecharge 话费兑换接口]
     * @param [type] $[id] [<充值卡的id>]
     * @return [type] [description]
     */
    public function applyphonecharge()
    {
        $u = $this->user;
        $user = User::where('id', $u['id'])->find();

        $cardid = $this->request->param('id');//充值卡的id
        $phonecard = PhonechargeList::where('id', $cardid)->find();//充值卡


        if (!$user || $user['balance'] < $phonecard['price']) {
            //用户余额不足
            return error([], '用户余额不足');
        }


        if (!$phonecard || $phonecard['count'] <= 0) {
            //充值卡数量不足
            return error([], '充值卡数量不足');
        }


        $history = Phonecharge::where('uid', $u['id'])->order('put_time', 'desc')->find();
        if ($history) {
            $time = strtotime($history['put_time']);
            $now = time() - $time;

            if ($now < 86400) {
                //今日已成功申请提现，请24小时后再次申请
                return error([], '今日已成功申请兑换，请24小时后再次申请');

            }
        }


        $money = $phonecard['price'];

        $out_balance = $user['balance'];
        $balance = $user['balance'] - $money;
        $count_price = Phonecharge::where('uid', $user['id'])->where('phonecharge_status', 2)->sum('price');
        // money 需要扣除手续费
        // $profit = Profit::where('id',1)->find();
        // // 手续费 百分比折扣 计算出需要多少手续费
        // $sxf = $money * $profit['fees'] / 100;
        // $money = $money - $sxf;
        $data = [
            'uid' => $user['id'],
            'username' => $user['username'],
            // 'account'=>$user['alipay'],
            // 'name'=>$user['name'],
            'price' => $money,
            'balance' => $balance,//充值后余额
            'out_balance' => $out_balance,//充值前余额
            'count_price' => $count_price,//累计充值额度
            'phonecharge_status' => 1,
            'put_time' => date('Y-m-d H:i:s'),
            'phonechargeid' => $cardid,
            'phonechargetype' => $phonecard['typename'],
            'remarks' => $user['remarks']
        ];
        $ret = Phonecharge::create($data);
        if ($ret) {

            PhonechargeList::where('id', $cardid)->dec('count')->update();//充值卡剩余数量减1
            // 扣除余额
            User::where('id', $user['id'])->update(['balance' => $balance]);
            return success([], '申请成功');
        } else {
            return error([], '申请失败');
        }


    }


    /**
     * [phonecharge_datalist 话费兑换记录 remarks为话费码]
     * @return [type] [description]
     */
    public function phonecharge_datalist()
    {
        $user = $this->user;
        $list = Phonecharge::where('uid', $user['id'])->order('id', 'desc')->select();
        return success($list);
    }


    /**
     * [change_account 支付宝账号绑定、修改接口 未绑定或者未曾修改则可以提交]
     * @param [type] $[alipay] [<支付宝账号>]
     * @param [type] $[name] [<支付宝姓名>]
     * @return [type] [description]
     */
    public function bind_account()
    {
        $u = $this->user;
        $user = User::where('id', $u['id'])->find();


        $alipay = $this->request->param('alipay');//充值卡的id
        $name = $this->request->param('name');//姓名


        $updataData = array(
            'alipay' => $alipay,
        );

        if (!empty($name)) {
            $updataData['name'] = $name;
        }


        if (empty($user['alipay'])) {

            User::where('id', $user['id'])->update($updataData);
            return success([], '绑定成功');

        } else if (!empty($user['alipay']) && $user['account_changed_times'] == 0) {

            $updataData['account_changed_times'] = 1;
            User::where('id', $user['id'])->update($updataData);
            return success([], '修改成功');

        } else {
            return error([], '您已经绑定过了');
        }

    }


    /**
     * [user_balance 用户余额接口]
     * @return [type] [description]
     */
    public function user_balance()
    {
        $u = $this->user;
        $user = User::where('id', $u['id'])->find();
        return success($user);

    }

    /**
     * User: 肥茹人士
     * Time: 2023/11/18 3:31
     * Notes:卡密兑换
     */
    public function user_cdkey()
    {

        $u = $this->user;
        $user = User::where('id', $u['id'])->find();

        $cdkey = $this->request->param('cdkey');

        $cdKeyinfo = Cdkey::where('key', $cdkey)->find();
        if (!$cdKeyinfo) {
            //卡密错误
            return error([], '卡密错误');
        }
        if ($cdKeyinfo['use_uid'] != 0) {
            return error([], '卡密已被使用');
        }
        $outTime = date('Y-m-d H:i:s', strtotime('+' . $cdKeyinfo['time'] . ' day'));


        $updataData = [
            'vip' => 1,
            'cdkey' => $cdkey,
            'out_time' => $outTime,
            'remarks' => $cdKeyinfo['remarks']
        ];
        User::where('id', $user['id'])->update($updataData);

        Cdkey::where('id', $cdKeyinfo['id'])->update(
            [
                'use_uid' => $u['id'],
                'use_username' => $u['username'],
                'active_time' => date('Y-m-d H:i:s'),
                'type' => 1
            ]
        );

        $user = User::where('id', $u['id'])->find();

        return success($user);

    }

    /**
     * User: 肥茹人士
     * Time: 2023/11/18 3:29
     * Notes:获取收益配置
     */
    public function profit()
    {
        $id = $this->request->param('id')??1;
        if(!$id)
        {
            return error([], '参数错误');
        }
        $res = Profit::where('id', $id)->find();
        if(!$res)
        {
            return error([], '参数错误');
        }
        return success($res);
    }


    /**
     * User: 肥茹人士
     * Time: 2023/11/18 3:29
     * Notes:获取奖励设置
     */
    public function config()
    {
        $id = $this->request->param('id')??1;
        if(!$id)
        {
            return error([], '参数错误');
        }
        $res = Config::where('id', $id)->find();
        if(!$res)
        {
            return error([], '参数错误');
        }
        return success($res);
    }


    /**
     * User: 肥茹人士
     * Time: 2023/9/17 22:23
     * Notes:传递计时
     */
    public function profirLog()
    {
        $id = $this->request->param('id') ?? 1;
        if(!$id)
        {
            return error([], '参数错误');
        }
        
        $u = $this->user;
        //查看收益
        $profit = Profit::where('id', $id)->find()->toArray();
        if(!$profit)
        {
            return error([], '参数错误');
        }

        $now = time();
        $date = date("Y-m-d H:i:s", $now);
        //查看下今日的收益记录
        $log_money = Profitlog::where('uid', $u['id'])->where('pid', $id)->where('date', "like", date("Y-m-d", $now)."%")->sum('money');

        if ($u['vip'] == 1) {
            $profit_money = $profit['day_count_vip'];
            $profit_time_price = $profit['min_add_vip'];
        } else {
            $profit_money = $profit['day_count'];
            $profit_time_price = $profit['min_add'];
        }

        $seconds = $this->request->param('second');
        //验证是不是倍数
        if ($seconds != $profit['time']) {
            return error([], '请通过正常渠道阅读');
        }


        #没有达到上限
        if ($log_money < $profit_money) {
            $rate = $profit_time_price / 60; // 每秒对应的金额
            // $seconds = $this->request->param('second');
            $totalAmount = $seconds * $rate;

            $totalAmount = round($totalAmount, 2); // 保留两位小数
            //     dump($u['id']);
            //      dump($totalAmount);
            // exit;
            if ($log_money + $totalAmount >= $profit_money) {
                $totalAmount = $profit_money - $log_money;
            }
            $save_data = [
                'uid' => $u['id'],
                'money' => $totalAmount,
                'date' => $date,
                'pid' => $id,
            ];
            Profitlog::create($save_data);

            UserMoneyLog::create([
                "type" => 1,
                'cate_id' => 2,
                "user_id" => $u['id'],
                "amount" => $totalAmount,
                "remark" => "看视频收益 +" . $totalAmount . "元"
            ]);

            //获取收益分成比例
            if(!empty($u['invite']))
            {
                $into = Db::name('config')->where('id',1)->value('into');
                $invite = User::where('id',$u['invite'])->find();
                if($invite)
                {
                    $invite_totalAmount = $totalAmount * $into / 100;
                    $invite->inc('balance', $invite_totalAmount)->update();

                    $save_data = [
                        'uid' => $u['invite'],
                        'money' => $invite_totalAmount,
                        'date' => $date,
                        'pid' => $id,
                        'from_id'=>$u['id']
                    ];
                    Profitlog::create($save_data);
                }
            }

            $res = User::where('id', $u['id'])->inc('freeze_money', $totalAmount)->update();
            return success([], '成功');

        } else {
            return error([], '已经达到今日收益上限',100);
        }


    }



}	